package com.xzx.springbootredis.controller;

import com.xzx.springbootredis.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("seckill")
public class SecKillController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //抢购
    @PostMapping("buy")
    public JsonResult buy(@RequestParam("goodsId") int goodsId, @RequestParam("memberId") int memberId) {
        //1.获取锁
        String lockKey = "goods-lock:" + goodsId;

        String uuid = UUID.randomUUID().toString();

        Boolean lockResult = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, uuid, 3, TimeUnit.SECONDS);

        if (Boolean.FALSE.equals(lockResult)) {
            return JsonResult.failed("抢票失败，请重试");
        }

        //2.判读库存
        String goodsStockKey = "goods-stock:"+goodsId;
        String stock = stringRedisTemplate.opsForValue().get(goodsStockKey);
        System.out.println(stock);
        if (stock == null || Integer.parseInt(stock) <= 0) {
            return JsonResult.failed("已经售罄");
        }

        //3.把会员id放到队列
        Long res = stringRedisTemplate.opsForList().leftPush("list-goods:" + goodsId, String.valueOf(memberId));
        //4.扣减库存
        if (res != null) {
            stringRedisTemplate.opsForValue().decrement(goodsStockKey,1);
        }
        //释放锁
        stringRedisTemplate.delete(lockKey);

        return JsonResult.success("抢票成功!",null);
    }

    //下单
    @PostMapping("creatOrder")
    public JsonResult createOrder(@RequestParam("goodsId") int goodsId) {
        String key = "list-goods:" + goodsId;
        String res = stringRedisTemplate.opsForList().rightPop(key);
        System.out.println(res);
        //生成订单

        return JsonResult.success("ok",null);


    }
}
